//
//  YBHomeVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2024/1/1.
//  Copyright © 2024 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import HandyJSON
import EachNavigationBar
import SVProgressHUD
import SwifterSwift

class YBHomeVC: BaseVC {
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    enum TopToolType: Int {
        case buy = 0
        case exchange
        case reset
        case loading
        case service
        case message
        case scan
        
        var style: (icon: String, des: String) {
            switch self {
            case .buy: return ("icon_home_buy", "购买")
            case .exchange: return ("icon_home_exchange", "兑换")
            case .reset: return ("icon_home_reset", "重置")
            case .loading: return ("icon_home_loading", "")
            case .service: return ("icon_home_service", "")
            case .message: return ("icon_home_message", "")
            case .scan: return ("icon_home_scan", "")
            }
        }
    }
    
    /// 当前选中的套餐
    private var currentSelectCombo = YBOrderInfoVosModel()
    private var topToolTypes: [TopToolType] = [.buy, .exchange, .reset]
    
    private var isOff: Bool = true {
        didSet {
            topToolTypes = isOff ? [.reset] : [.buy, .exchange, .reset]
            layoutBtnStackView.removeAllSubviews()
            topToolTypes.forEach { type in
                let item = createTopToolItem(type: type)
                layoutBtnStackView.addArrangedSubview(item)
            }
            
            layoutBtnStackView.snp.updateConstraints { make in
                make.size.equalTo(CGSizeMake(60*2+12.5*1, 24.5))
            }
        }
    }
    
    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigation.bar.alpha = 0
        navigation.bar.isHidden = true
        
        topToolTypes.forEach { type in
            let item = createTopToolItem(type: type)
            layoutBtnStackView.addArrangedSubview(item)
        }
        
        view.addSubview(bgImgView)
        bgImgView.addSubviews([layoutBtnStackView, btnStackView, packageTimeLimitLabel, durationRemainingLabel, lineImgView, poweronBtn, cardView, emptyComboImgView1, emptyComboImgView2])
        
        bgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        layoutBtnStackView.snp.makeConstraints { make in
            make.left.equalTo(18.5).priority(.high)
            make.top.equalTo(kStatusBarHeight+30)
            make.size.equalTo(CGSizeMake(60*3+12.5*2, 24.5))
        }
        
        btnStackView.snp.makeConstraints { make in
            make.centerY.equalTo(layoutBtnStackView)
            make.right.equalTo(-18)
            make.size.equalTo(CGSizeMake(15*4 + 15*3, 15))
        }
        
        packageTimeLimitLabel.snp.makeConstraints { make in
            make.left.equalTo(18.5)
            make.top.equalTo(layoutBtnStackView.snp.bottom).offset(21)
            make.height.equalTo(13)
        }
        
        durationRemainingLabel.snp.makeConstraints { make in
            make.right.equalTo(-18.5)
            make.centerY.height.equalTo(packageTimeLimitLabel)
        }
        
        lineImgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(packageTimeLimitLabel.snp.bottom).offset(40)
            make.height.equalTo(10)
        }
        
        emptyComboImgView1.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(lineImgView.snp.bottom).offset(34)
        }
        
        emptyComboImgView2.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(emptyComboImgView1.snp.bottom).offset(12)
        }
        
        cardView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.centerX.equalToSuperview()
            make.top.equalTo(lineImgView.snp.bottom).offset(55)
            make.height.equalTo(156.5)
        }
        
        poweronBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(cardView.snp.bottom).offset(72)
            make.size.equalTo(CGSizeMake(170, 28))
        }
        
        self.get_gameClientInfo()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.bk_setBackBarButtonItem(isHidden: true)
        
        vm.req_popSwitch { [weak self] ok, obj, msg, code in
            if ok {
                guard let self = self,
                      let js = obj as? JSON,
                      let data = js[NetDataKey].string else { return }
                if data == "off" {
                    isOff = true
                }
            } else {
                self?.isOff = true
            }
        }
    }
    
    private func createTopToolItem(type: TopToolType) -> BKLayoutButton {
        let btn = self.bk_addLayoutButton(space: 6, bgColor: .clear, imageSize: CGSizeMake(13, 12), image: UIImage(named: type.style.icon), titleFont: .systemFont(ofSize: 11), title: type.style.des, titleColor: kRGBColor(184, 169, 136))
        btn.bk_setEnlargeEdge(10)
        btn.setBackgroundImage(UIImage(named: "icon_home_button_border"), for: .normal)
        btn.bk_addTarget { [weak self] sender in
            guard let self = self else { return }
            switch type {
            case .buy:
                let vc = YBBuyPopupVC()
                self.present(vc, animated: true)

            case .exchange:
                let vc = YBActivationCodePopupVC()
                vc.onDismiss = { [weak self] in
                    self?.get_gameClientInfo()
                }
                self.present(vc, animated: true)

            case .reset:
                let vc = YBDeviceResetPopupVC()
                self.present(vc, animated: true)
            default:
                break
            }
        }
        return btn
    }
    
    // MARK: - lazy
    lazy var vm: YBHomeViewModel = {
        let vm = YBHomeViewModel()
        return vm
    }()
    
    private lazy var bgImgView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_home_bg_s"))
        iv.isUserInteractionEnabled = true
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var emptyComboImgView1: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_home_empty_combo1"))
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var emptyComboImgView2: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_home_empty_combo2"))
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var layoutBtnStackView: UIStackView = {
        let _stackView = UIStackView()
        _stackView.axis = .horizontal
        _stackView.spacing = 12.5
        _stackView.alignment = .fill
        _stackView.distribution = .fillEqually
        return _stackView
    }()
    
    private lazy var btnStackView: UIStackView = {
        let arr: [TopToolType] = [.loading, .service, .message, .scan]
        var btns = [UIButton]()
        arr.forEach { type in
            let btn = UIButton(type: .custom)
            btn.bk_setEnlargeEdge(5)
            btn.setImage(UIImage(named: type.style.icon), for: .normal)
            btn.bk_addTarget { [weak self] sender in
                guard let self = self else { return }
                switch type {
                case .loading:
                    get_gameClientInfo()
                case .service:
                    let vc = YBCloudComputerFeedbackPopupVC()
                    vc.configBlock = { [weak self] text, type in
                        let parm = ["content": text, "type": type + 1]
                        self?.vm.req_Gzbx(parm) { ok, obj, msg, code in
                            if ok {
                                HintTool.toast("反馈成功")
                            } else {
                                HintTool.toast(msg)
                            }
                        }
                    }
                    self.present(vc, animated: true)
                case .message:
                    let messageVC = YBMessageVC()
                    self.navigationController?.pushViewController(messageVC, animated: true)
                case .scan:
                    break
                default:
                    break
                }
            }
            btns.append(btn)
        }
        let view = UIStackView(arrangedSubviews: btns, axis: .horizontal, spacing: 15, alignment: .fill, distribution: .fillEqually)
        return view
    }()
    
    private lazy var packageTimeLimitLabel = self.bk_addLabel(text: "套餐时限：2023年12月15日", font: .systemFont(ofSize: 11), bgColor: .clear, textColor: kRGBColor(189, 192, 200))
    
    private lazy var durationRemainingLabel = self.bk_addLabel(text: "时长剩余：1天23小时15分钟", font: .systemFont(ofSize: 11), bgColor: .clear, textColor: kRGBColor(189, 192, 200))
    
    private lazy var lineImgView: UIImageView = {
        let iv = UIImageView(image: UIImage(named: "icon_home_line"))
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var cardView: BKCardView = {
        let cardView = BKCardView()
        cardView.pagingEnabled = true
        cardView.isAutoScroll(false)
        cardView.isInfinite(false)
        cardView.delegate = self
        cardView.dataSource = self
        cardView.setMiniLineSpace(20)
        cardView.setFlowlayout(wScale: 0.392, hScale: 1)
        cardView.setStyle(by: .center)
        cardView.register(cellWithClass: YBHomePackageCell.self)
        return cardView
    }()
    
    private lazy var poweronBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage(named: "icon_home_poweron"), for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 12)
        btn.setTitle("开机启动", for: .normal)
        btn.setTitleColor(kRGBColor(184, 169, 136), for: .normal)
        btn.bk_addTarget { [weak self] sender in
            guard let self = self else { return }
            if self.vm.gameClientInfoModel.orderInfoVos.isEmpty {
                let vc = YBBuyPopupVC()
                self.present(vc, animated: true)
            } else {
                if isOff {
                    self.vm.req_OpenPC(self.currentSelectCombo)
                } else {
                    self.get_GetQueueNum()
                }
            }
        }
        return btn
    }()
    
}

// MARK: - BKCardView代理
extension YBHomeVC: BKCardViewDataSource, BKCardViewDelegate {
    
    func cardSwitchNumberOfCard() -> Int {
        return vm.gameClientInfoModel.orderInfoVos.count
    }
    
    func cardSwitchCellForItemAtIndex(index: Int) -> UICollectionViewCell {
        let cell = cardView.dequeueReusableCell(withClass: YBHomePackageCell.self, for: index)
        if let model = vm.gameClientInfoModel.orderInfoVos[safe: index] {
            cell.updateCell(by: model, isRecommend: index == 0)
        }
        return cell
    }
    
    func cardSwitchDidSelectedAtIndex(index: Int) {
        if let model = vm.gameClientInfoModel.orderInfoVos[safe: index] {
            currentSelectCombo = model
        }
    }
    
}

// MARK: - 网络请求
extension YBHomeVC {
    
    fileprivate func get_gameClientInfo() {
        SVProgressHUD.show(withStatus: "请求中...")
        vm.req_GameClientInfo { [weak self] ok, obj, msg, code in
            if ok {
                guard let self = self,
                      let js = obj as? JSON,
                      let data = js[NetDataKey].dictionaryObject,
                      let model = YBGameClientInfoModel.deserialize(from: data) else { return }
                self.vm.gameClientInfoModel = model
                self.bgImgView.image = model.orderInfoVos.isEmpty ? UIImage(named: "icon_home_bg_s_empty") : UIImage(named: "icon_home_bg_s")
                self.cardView.isHidden = model.orderInfoVos.isEmpty
                
                self.emptyComboImgView1.isHidden = !model.orderInfoVos.isEmpty
                self.emptyComboImgView2.isHidden = !model.orderInfoVos.isEmpty
                self.packageTimeLimitLabel.text = "套餐时限：\(model.endTime)"
                self.durationRemainingLabel.text = "时长剩余：\(model.surplusTotal)"
                if !model.orderInfoVos.isEmpty, let firstModel = model.orderInfoVos.first {
                    SVProgressHUD.showSuccess(withStatus: "请求成功")
                    self.cardView.reloadData()
                    self.currentSelectCombo = firstModel
                    TaskTool.delay(0.35) {
                        self.cardView.selectItem(item: 0)
                    }
                }else {
                    SVProgressHUD.showError(withStatus: "暂无套餐信息")
                }
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
    /// 获取当前的排队
    fileprivate func get_GetQueueNum() {
        vm.req_GetQueueNum(currentSelectCombo.type.string) { [weak self] ok, obj, msg, code in
            if ok {
                guard let self = self,
                      let js = obj as? JSON,
                      let data = js[NetDataKey].int else { return }
                if data > 0 { // 排队
                    let vc = YBQueuePopupVC(type: self.currentSelectCombo.type, queueNum: data)
                    self.present(vc, animated: true)
                } else {
                    if self.currentSelectCombo.purchase {
                        self.vm.req_OpenPC(self.currentSelectCombo)
                    } else {
                        let vc = YBCloudComputerBuyVC(goodsId: self.currentSelectCombo.goodsId)
                        self.navigationController?.pushViewController(vc)
                    }
                }
            } else {
                HintTool.toast(msg)
            }
        }
    }
    
}
